package B_Splain;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;

public class MyFlame extends JFrame {
    JScrollPane scrollPane ;
    private int wight = 800;
    private int height = 600;
    DataPanel dataPanel = new DataPanel();
    private Point2D draggedPoint = null; // 当前正在拖动的点
    GraphPanel graphPanel = new GraphPanel();

    ArrayList<Point2D> points = new ArrayList<>();//数据面板选中的点

    public MyFlame() {
//窗口本身
        scrollPane = new JScrollPane(dataPanel);
        add(scrollPane, BorderLayout.WEST);
        // 设置窗口标题为"B样条拟合曲线"
        setTitle("B样条拟合曲线");
        // 设置窗口的大小
        setSize(wight, height);
        // 设置窗口关闭时的默认操作为退出程序
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 将窗口位置设置为中心位置
        setLocationRelativeTo(null);
        // 设置窗口背景颜色为白色
        setBackground(Color.WHITE);
        // 设置窗口的布局管理器为BorderLayout
        setLayout(new BorderLayout());
        //设置窗口禁止缩放
        setResizable(false);
        // 将GraphPanel添加到窗口的东边
        add(graphPanel,BorderLayout.CENTER);
//数据面板
        // 将DataPanel添加到窗口的西边
        add(dataPanel,BorderLayout.WEST);
        // 为 JList 添加 ListSelectionListener
        dataPanel.list.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                points.clear();
                graphPanel.repaint();
                if (!e.getValueIsAdjusting()) { // 避免在选择过程中多次触发
                    ListSelectionModel listSelectionModel = dataPanel.list.getSelectionModel();
                    int firstIndex = listSelectionModel.getMinSelectionIndex();
                    int lastIndex = listSelectionModel.getMaxSelectionIndex();
                    System.out.println(firstIndex + " " + lastIndex);

                    if (firstIndex == -1) {
                        // 没有选中项
//                        JOptionPane.showMessageDialog(, "No item selected");
                    } else {
                        for (int i = firstIndex; i <= lastIndex; i++) {
                            Point2D point = dataPanel.pointList.get(i);
                            points.add(point);
                        }
                        graphPanel.tempPoints = points;
                        graphPanel.repaint();
//                        JOptionPane.showMessageDialog(frame, "Selected Point: x=" + selectedPoint.getX() + ", y=" + selectedPoint.getY());
                    }
                }
            }
        });






//图形面板
        graphPanel.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                if (draggedPoint != null) {
                    // 更新点的位置
                    draggedPoint.setLocation(e.getX(), e.getY());
                    repaint(); // 重绘面板以显示新位置
                }
            }
        });

        graphPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                draggedPoint = null;
                // 检查是否点击了某个点
                for (Point2D point : points) {
                    if (isPointNear(point, e.getX(), e.getY())) {
                        draggedPoint = getNearestPoint(point, draggedPoint , e.getX(), e.getY());
                    }
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                try {
                    draggedPoint.setLocation(e.getX(), e.getY()); // 释放鼠标时停止拖动
                    ok();
                    graphPanel.paintPoint((Graphics2D) graphPanel.getGraphics(),new Color(255, 0, 0),draggedPoint,6);
                }catch (Exception ex){
                    System.out.println("没有点被拖动");
                }

            }

            @Override
            public void mouseClicked(MouseEvent e) {
                Point2D point = new Point2D.Double(e.getX(), e.getY());
                // 点击事件，在控制台输出坐标
                System.out.println("x = " + e.getX() + ", y = " + e.getY());
                // 点击事件，将坐标添加到ArrayList中
                graphPanel.pointList.add(point);
                graphPanel.paintPoint((Graphics2D) graphPanel.getGraphics(),new Color(255, 0, 0),point,5);
                dataPanel.addPoint(point);
                graphPanel.currenPpoint =null;
//                graphPanel.repaint();
            }
        });
        // 创建一个确定按钮
        JButton okButton = new JButton("确定");
        //创建一个取消按钮
        JButton cancelButton = new JButton("取消");
        //创建一个删除按钮
        JButton delateButton = new JButton("删除");
        //创建一个合并按钮
        JButton mergeButton = new JButton("合并");

        //给确定按钮添加点击事件
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    ok();
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }

            }
        });

        //给取消按钮添加点击事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 在这里处理取消按钮的点击事件
                System.out.println("取消按钮被点击了！");
                try {
                    clear(okButton, cancelButton, delateButton);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        //给删除按钮添加点击事件
        delateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                delate();
                try {
                    ok(okButton, cancelButton, delateButton);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        //给合并按钮添加点击事件
        mergeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < graphPanel.partList.size(); i++) {
                    List<Point2D> point2DS = graphPanel.partList.get(i);
                    if (!point2DS.containsAll(points) && point2DS.size() != 0){
                        graphPanel.partList.get(i).addAll(graphPanel.partList.get(i + 1));
                        graphPanel.partList.remove(i + 1);
                    }
                }
                try {
                    ok(okButton, cancelButton, delateButton);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });


        // 将确定按钮添加到面板的底部
        graphPanel.add(okButton, BorderLayout.SOUTH);
        // 将取消按钮添加到面板的底部
        graphPanel.add(cancelButton, BorderLayout.SOUTH);
        // 将删除按钮添加到面板的底部
        graphPanel.add(delateButton, BorderLayout.SOUTH);
        // 将合并按钮添加到面板的底部
        graphPanel.add(mergeButton, BorderLayout.SOUTH);

        // 设置窗口为可见
        setVisible(true);


    }



    private Point2D getNearestPoint(Point2D point, Point2D draggedPoint, int x, int y) {
        if (draggedPoint == null) {
            return point;
        }
        double distance1 = draggedPoint.distance(x, y);
        double distance2 = point.distance(x, y);
        if (distance1 < distance2) {
            return draggedPoint;
        } else {
            return point;
        }
    }


    //取消按钮
    public void clear(JButton... jButtons) throws InterruptedException {
        //清空所有点的数据
        graphPanel.pointList.clear();
        dataPanel.pointList.clear();
//        graphPanel.curvePoints.clear();
        graphPanel.currenPpoint = null;
        graphPanel.partList.clear();
        //刷新面板
        graphPanel.repaint();
        setButtunVisible(jButtons);//刷新后再将按钮显示出来
    }

    //确定按钮
    public void ok(JButton ... buttons) throws InterruptedException {
        graphPanel.partList.add(graphPanel.pointList);
        graphPanel.pointList = new ArrayList<>();


        graphPanel.paintCurve((Graphics2D) graphPanel.getGraphics());
        graphPanel.currenPpoint = null;
        graphPanel.currenPpoint = null;
        graphPanel.repaint();
        setButtunVisible(buttons);
    }

    //删除按钮
    private void delate() {
        if (graphPanel.currenPpoint == null)return;
        for (List<Point2D> point2DS : graphPanel.partList) {
            if (point2DS.contains(draggedPoint)) {
                point2DS.remove(graphPanel.currenPpoint);
                break;
            }
        }
//        System.out.println(graphPanel.pointList.remove(draggedPoint));
        System.out.println(dataPanel.pointList.removeElement(draggedPoint));
        graphPanel.currenPpoint = null;
    }

    // 辅助方法：检查点是否在鼠标位置附近
    private boolean isPointNear(Point2D point, int x, int y) {
        int radius = 5; // 捕获范围
        return Math.abs(point.getX() - x) <= radius && Math.abs(point.getY() - y) <= radius;
    }

    public void setButtunVisible(JButton... buttons) {
        super.repaint();
        for (JButton button1 : buttons) {
            button1.setVisible(true);
        }
    }
}
